<template>
	<div class="container add_edit">
		<el-form v-loading="formLoading" :disabled="addBtnLoading" :model="form" ref="ruleForm" label-width="50px">
			<el-form-item label="类型">
				<el-radio-group v-model="form.type">
					<el-radio label="网页">网页</el-radio>
					<el-radio label="内容">内容</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="网页" v-show="form.type == '网页'">
				<el-input v-model="form.url" placeholder="请输入网页地址" clearable></el-input>
			</el-form-item>
			<el-form-item label="内容" v-show="form.type == '内容'">
				<use-editor :disabled="addBtnLoading" ref="editor" @editorChange="editorChange"></use-editor>
			</el-form-item>
			<el-form-item>
				<el-button :loading="addBtnLoading" round icon="el-icon-check" class="confirm-btn"
					@click="submitForm('ruleForm')">提交</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	const __name = 'usemall-app-about';
	export default {
		data() {
			return {
				dataId: '',
				formLoading: false,
				form: {
					type: '网页',
					url: '',
					content: '',
					state: '启用'
				},
				addBtnLoading: false
			};
		},
		methods: {
			async loadData() {
				this.formLoading = true;
				await this.$db[__name].tofirst({
					loading: false
				}).then(res => {
					if (res.code == 200) {
						res.datas = res.datas || {};
						this.dataId = res.datas._id;

						if (Object.keys(res.datas).length) {
							for (let item in this.form) {
								this.form[item] = res.datas[item];
							}

							if (res.datas && res.datas.content) {
								this.form.content = res.datas.content;
								this.$refs.editor.setContent(this.form.content);
							}
						}
					}
					this.formLoading = false;
				});
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					// 默认获取第一个未验证 form 属性名
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.addBtnLoading = true;
						if (!this.dataId) {
							this.$db[__name].add(this.form).then(res => {
								if (res.code == 200) {
									this.$message({
										message: '操作成功',
										type: 'success'
									});
									this.addBtnLoading = false;
									return;
								}
								this.loadData();
							}).catch(() => {
								this.addBtnLoading = false;
							})
						} else {
							this.$db[__name].update(this.dataId, this.form).then(res => {
								if (res.code == 200) {
									this.$message({
										message: '操作成功',
										type: 'success'
									});
									this.addBtnLoading = false;
									return;
								}
								this.loadData();
							}).catch(() => {
								this.addBtnLoading = false;
							})
						}
					}
				});
			},
			editorChange(res) {
				this.form.content = res;
			}
		},
		created() {
			this.loadData();
		}
	};
</script>

<style></style>
